<script>
export default {
  name: "AdoptionPage",
  data() {
    return {
      isAdopting: false,
      adoptReason: '',
      userInfo: null,
      searchKeyword: '',
      selectedSpecies: null,
      selectedGender: null,
      selectedPet: null,
      table: false,
      dialog: false,
      loading: false,
      gridData: [],
      disabled:false,
      showAdoptForm: false, // 控制弹窗显示
      searchDebounce: null, // 防抖定时器
      speciesOptions: [
        { value: 6 , label: '猫咪' },
        { value: 4 , label: '狗狗' },
      ],
      genderOptions: [
        { value: 1 , label: '男生' },
        { value: 2 , label: '女生' }
      ],
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '80px',
      timer: null,
      // 静态数据
      pets: [],
    }
  },
  mounted() {
    this.loadPets(); // 初始化加载
  },
  computed: {
    filteredPets() {
      return this.pets.filter(pet => {
        // 关键字搜索（宠物名称，不区分大小写）
        const keywordMatch = this.searchKeyword.trim() === '' ||
            pet.petName.toLowerCase().includes(this.searchKeyword.toLowerCase());

        // 种类筛选（支持空值）
        const speciesMatch = !this.selectedSpecies ||
            pet.petType === this.selectedSpecies;

        // 性别筛选（支持空值）
        const genderMatch = !this.selectedGender ||
            pet.sex === this.selectedGender;

        // 领养状态筛选（仅显示未处理的申请）
        const statusMatch = pet.applyStatus !== 1; // 假设1表示已通过

        return keywordMatch && speciesMatch && genderMatch && statusMatch;
      });
    },
  },
  methods: {
    /*加载宠物数据*/
    async loadPets() {
      this.loading = true;
      try {
        const res = await this.$axios.post(this.$httpUrl + '/pet/listPageP', {
          pageNum: 1,
          pageSize: 10,
          param: {
            keywords: this.searchKeyword.trim(),
            petType: this.selectedSpecies, // 对应 6（猫）或 4（狗）
            sex: this.selectedGender
          }
        });
        if (res.data.code === 200) {
          this.pets = res.data.data
              .filter(pet => pet.applyStatus !== 1) // 过滤已领养的宠物
              .map(pet => ({
            ...pet,
            imageUrl: `${this.$httpUrl}/pet/image/${pet.id}?t=${Date.now()}`, // 动态图片地址
            speciesText: this.getSpeciesText(pet.petType), // 类型文本
            genderText: pet.sex === 1 ? '♂ 男生' : '♀ 女生', // 性别文本
            statusText: this.getStatusText(pet.status) // 状态文本
          }));
        }
      } catch (error) {
        this.$message.error('数据加载失败');
      } finally {
        this.loading = false;
      }
    },
    // 点击“领养 ta”按钮时触发
    openAdoptForm() {
      if (!this.$store.state.user) {
        this.$message.error('请先登录！');
        return;
      }
      this.showAdoptForm = true;
    },
    // 类型转换
    getSpeciesText(type) {
      return type === 4 ? '小狗' : type === 6 ? '小猫' : '未知';
    },
    // 状态转换
    getStatusText(status) {
      const statusMap = {
        200: '健康',
        400: '疾病',
      };
      return statusMap[status] || '未知状态';
    },
    // 搜索方法
    handleSearch() {
      if (this.searchDebounce) {
        clearTimeout(this.searchDebounce);
      }
      this.searchDebounce = setTimeout(() => {
        this.loadPets();
      }, 300); // 延迟 300ms 执行
    },
    // 打开抽屉显示详情
    showPetDetail(pet) {
      this.selectedPet = pet;
      this.table = true;
    },
    Finish() {
      this.$router.replace("/")
    },
    // 重置所有筛选条件
    resetFilters() {
      this.searchKeyword = '';
      this.selectedSpecies = null;
      this.selectedGender = null;
      this.loadPets(); // 重新加载数据
    },
    // 提交领养申请
    async handleAdopt() {
      if (!this.adoptReason.trim()) {
        this.$message.error('请填写领养理由');
        return;
      }
      try {
        const formData = new FormData();
        formData.append('petNo', this.selectedPet.petNo); // 确保参数名与后端一致
        formData.append("petName",this.selectedPet.petName);
        formData.append('adopterNo', this.$store.state.user.no);
        formData.append('content', this.adoptReason);
        const res = await this.$axios.post(
            this.$httpUrl +'/adoption/submit', formData);
        if (res.data.code === 200) {
          this.$message.success('领养申请已提交，请等待审核');
          this.disabled = true;
          this.showAdoptForm = false;
          this.table = false; // 关闭抽屉
        }
      } catch (error) {
        this.$message.error('提交失败: ' + error.response?.data?.msg);
      }
    },
  }
}
</script>

<template>
  <div class="adoption-page">
    <header class="header">
      <el-link :underline="false"
               class="back-link"
               @click.native="Finish"
               icon="el-icon-back"
      >
      </el-link>
      <h1 class="title">Furever & Family</h1>
    </header>
    <div class="divider"></div>
    <!-- 顶部搜索和筛选区域 -->
    <el-row :gutter="20" class="filter-bar">
      <!-- 搜索框 -->
      <el-col :span="8">
        <el-input
            v-model="searchKeyword"
            placeholder="搜索宠物名字..."
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
        </el-input>
      </el-col>

      <!-- 种类筛选 -->
      <el-col :span="6">
        <el-select
            v-model="selectedSpecies"
            placeholder="选择种类"
            @change="handleSearch"
        >
          <el-option
              v-for="species in speciesOptions"
              :key="species.value"
              :label="species.label"
              :value="species.value"
          />
        </el-select>
      </el-col>

      <!-- 性别筛选 -->
      <el-col :span="6">
        <el-select
            v-model="selectedGender"
            placeholder="选择性别"
            @change="handleSearch"

        >
          <el-option
              v-for="gender in genderOptions"
              :key="gender.value"
              :label="gender.label"
              :value="gender.value"
          />
        </el-select>
      </el-col>
      <!-- 重置按钮 -->
      <el-col :span="4">
        <el-button @click="resetFilters">重 置</el-button>
      </el-col>
    </el-row>

    <!-- 宠物卡片网格布局 -->
    <el-row :gutter="20" class="pet-grid">
      <el-col
          v-for="pet in pets"
          :key="pet.id"
          :xs="12"
          :sm="8"
          :md="6"
          class="pet-card-col"
      >
        <el-card class="pet-card" shadow="hover">
          <el-image
              :src="pet.imageUrl"
              fit="cover"
              class="pet-image"
          >
            <div v-if="!pet.imageUrl" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>

          <div class="pet-info">
            <h3 class="pet-name">{{ pet.petName }}</h3>
            <div class="pet-meta">
              <span class="species">{{ pet.speciesText }}</span>
              <el-tag
                  :type="pet.sex === 1 ? 'primary' : 'danger'"
                  size="mini"
              >
                {{ pet.genderText }}
              </el-tag>
            </div>
            <div class="pet-no">编号：{{ pet.petNo }}</div>
          </div>
          <el-button type="text" @click="showPetDetail(pet)">去看看ta</el-button>
        </el-card>
      </el-col>
    </el-row>
    <div>
      <!--Drawer抽屉区-->
      <el-drawer
          :title="selectedPet?.petName || '详情'"
          :visible.sync="table"
          direction="rtl"
          size="50%">
        <div v-if="selectedPet" class="drawer-content">
          <img :src="selectedPet.imageUrl" class="detail-image">
          <div class="detail-meta">
            <h2 class="detail-title">{{ selectedPet.petName }}</h2>
            <div class="info">
              <span>编号：{{ selectedPet.petNo }}</span>
              <el-tag type="info">{{ selectedPet.speciesText }}</el-tag>
              <el-tag :type="selectedPet.sex === 1 ? 'primary' : 'danger'">
                {{ selectedPet.genderText }}
              </el-tag>
            </div>
            <div class="status">
              <el-tag :type="selectedPet.status === 200 ? 'success' : 'danger'">
                {{ selectedPet.statusText }}
              </el-tag>
            </div>
            <div class="detail-content">
              {{ selectedPet.content || '暂无详细描述' }}
            </div>
          </div>
        </div>
        <div class="demo-drawer__footer">
          <el-button type="success"
                     @click="openAdoptForm"
                     :disabled="isAdopting"
                     style="margin-left: 20px"
          >{{  isAdopting ? '提交中 ...' : '领 养 ta' }}</el-button>
        </div>
      </el-drawer>
    </div>
    <el-dialog
        title="填写领养理由"
        :visible.sync="showAdoptForm"
        width="30%"
    >
      <el-input
          type="textarea"
          v-model="adoptReason"
          placeholder="请输入领养理由..."
          :rows="4"
      ></el-input>
      <span slot="footer">
    <el-button @click="showAdoptForm = false">取消</el-button>
    <el-button type="primary" @click="handleAdopt">提交</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<style scoped>
.adoption-page {
  padding: 20px;
  background-color: #FFF3E0
}
.back-link {
  position: absolute;
  left: 10px;
  z-index: 1;
  /deep/ .el-icon-back {
    margin-right: 5px;
  }
}

.filter-bar {
  margin-top: 12px;
  margin-bottom: 18px;
}

.pet-grid {
  margin: 0 -10px;
}

.pet-card-col {
  padding: 10px;
}

.pet-card {
  transition: transform 0.3s;
  cursor: pointer;
}

.pet-card:hover {
  transform: translateY(-5px);
}

.pet-image {
  height: 200px;
  width: 100%;
  border-radius: 4px 4px 0 0;
}

.image-slot {
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #909399;
}

.pet-info {
  padding: 15px;
}

.pet-name {
  margin: 0 0 10px;
  color: #303133;
  font-size: 18px;
}

.pet-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.species {
  color: #606266;
  font-size: 14px;
}

.pet-no {
  color: #909399;
  font-size: 12px;
}
.title {
  color: #66BB6A ;
  font-size: 1.5rem;
  font-weight: 600;
  letter-spacing: 1px;
  text-align: left;
  margin-left: 40px;
}
.divider {
  border-bottom: 1px solid #BDBDBD;
  margin: 0 auto;
  width: 100%;
}
/* 详情页样式 */
.drawer-content {
  padding: 20px;
}
.detail-image {
  width: 100%;
  max-height: 300px;
  object-fit: cover;
  border-radius: 8px;
}
.detail-meta {
  margin-top: 15px;
}
.detail-title {
  color: #333;
  margin-bottom: 15px;
}
.info {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
}
.detail-content {
  margin-top: 20px;
  line-height: 1.8;
  white-space: pre-wrap;
  padding: 15px;
  background: #f8f8f8;
  border-radius: 4px;
}
</style>